#!/usr/bin/env python3
"""
Diagnostic script for checking Chrome and ChromeDriver setup.
"""

import sys
import os
import platform
import subprocess
import logging
from pathlib import Path
from typing import Dict, Any, Optional
import psutil
import json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import WebDriverException

def setup_logging():
    """Configure logging for diagnostics"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler('diagnostic.log')
        ]
    )

def get_chrome_version() -> Optional[str]:
    """Get installed Chrome version"""
    system = platform.system()
    try:
        if system == "Darwin":  # macOS
            process = subprocess.run(
                ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '--version'],
                capture_output=True,
                text=True
            )
            return process.stdout.strip()
        elif system == "Linux":
            process = subprocess.run(['google-chrome', '--version'], capture_output=True, text=True)
            return process.stdout.strip()
        elif system == "Windows":
            process = subprocess.run(
                ['reg', 'query', 'HKEY_CURRENT_USER\\Software\\Google\\Chrome\\BLBeacon', '/v', 'version'],
                capture_output=True,
                text=True
            )
            return process.stdout.strip()
    except Exception as e:
        logging.error(f"Failed to get Chrome version: {e}")
        return None

def check_chromedriver(path: Optional[str] = None) -> bool:
    """Check if ChromeDriver is working"""
    try:
        if path:
            process = subprocess.run([path, '--version'], capture_output=True, text=True)
        else:
            driver_path = ChromeDriverManager().install()
            process = subprocess.run([driver_path, '--version'], capture_output=True, text=True)
        logging.info(f"ChromeDriver version: {process.stdout.strip()}")
        return True
    except Exception as e:
        logging.error(f"ChromeDriver check failed: {e}")
        return False

def test_webdriver_connection():
    """Test basic WebDriver functionality"""
    driver = None
    try:
        logging.info("Testing WebDriver connection...")
        
        options = webdriver.ChromeOptions()
        options.add_argument("--headless")
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-dev-shm-usage")
        options.add_argument("--disable-gpu")
        options.add_argument("--log-level=3")
        
        service = Service(
            ChromeDriverManager().install(),
            log_path='chromedriver_test.log',
            service_args=['--verbose']
        )
        
        driver = webdriver.Chrome(service=service, options=options)
        driver.set_page_load_timeout(30)
        
        # Test with a simple page
        driver.get("data:text/html,<html><body><h1>Test Page</h1></body></html>")
        logging.info("Basic WebDriver test successful")
        return True
        
    except Exception as e:
        logging.error(f"WebDriver test failed: {e}")
        return False
    finally:
        if driver:
            driver.quit()

def check_system_resources():
    """Check system resources"""
    memory = psutil.virtual_memory()
    cpu_percent = psutil.cpu_percent(interval=1)
    disk = psutil.disk_usage('/')
    
    logging.info("System Resources:")
    logging.info(f"Memory: {memory.percent}% used ({memory.available / 1024 / 1024:.2f} MB available)")
    logging.info(f"CPU Usage: {cpu_percent}%")
    logging.info(f"Disk Space: {disk.percent}% used")
    
    return {
        'memory_available_mb': memory.available / 1024 / 1024,
        'cpu_percent': cpu_percent,
        'disk_percent': disk.percent
    }

def kill_chromedriver_processes():
    """Kill any running ChromeDriver processes"""
    killed = False
    for proc in psutil.process_iter(['name']):
        try:
            if 'chromedriver' in proc.info['name'].lower():
                proc.kill()
                killed = True
                logging.info(f"Killed ChromeDriver process: {proc.pid}")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return killed

def main():
    """Run diagnostic tests"""
    setup_logging()
    logging.info("=== Starting Diagnostics ===")
    
    # Check system information
    logging.info(f"Platform: {platform.platform()}")
    logging.info(f"Python version: {sys.version}")
    
    # Check Chrome version
    chrome_version = get_chrome_version()
    if chrome_version:
        logging.info(f"Chrome version: {chrome_version}")
    else:
        logging.error("Chrome not found")
        return
    
    # Check system resources
    resources = check_system_resources()
    
    # Kill existing ChromeDriver processes
    if kill_chromedriver_processes():
        logging.info("Cleaned up existing ChromeDriver processes")
    
    # Check ChromeDriver
    chromedriver_path = "/opt/homebrew/bin/chromedriver"  # 使用配置文件中的路径
    if check_chromedriver(chromedriver_path):
        logging.info("ChromeDriver check passed")
    else:
        logging.error("ChromeDriver check failed")
        return
    
    # Test WebDriver connection
    if test_webdriver_connection():
        logging.info("WebDriver connection test passed")
    else:
        logging.error("WebDriver connection test failed")
    
    logging.info("=== Diagnostics Complete ===")

if __name__ == "__main__":
    main() 